package com.simple.mq.boot.starter.config;

import cn.hutool.core.collection.CollectionUtil;
import com.simple.mq.boot.starter.ConsumerInitEvent;
import com.simple.mq.boot.starter.InitAnnotationBeanPostProcessor;
import com.simple.mq.boot.starter.util.MqSendUtil;
import com.simple.mq.common.entity.RegisterQueueInfo;
import com.simple.mq.sdk.register.RegisterConnectInfo;
import com.simple.mq.sdk.register.SimpleRegister;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 项目: simple-mq
 * <p>
 * 功能描述:
 *
 * @author: WuChengXing
 * @create: 2023-09-16 22:52
 **/
@Configuration
@EnableConfigurationProperties({SimpleQueueInitConfig.class, SimpleMqCommonConfig.class})
public class SimpleMqAutoConfig {

    @Resource
    private SimpleMqCommonConfig simpleMqCommonConfig;

    @Bean
    public Object initConfig(SimpleQueueInitConfig simpleQueueInitConfig) {
        if (Objects.isNull(simpleQueueInitConfig)) {
            return null;
        }
        if (CollectionUtil.isEmpty(simpleQueueInitConfig.getQueues())) {
            return null;
        }
        Map<String, String> queues = simpleQueueInitConfig.getQueues();
        Boolean rewrite = simpleQueueInitConfig.getRewrite();
        SimpleRegister.init(transfer(simpleMqCommonConfig));
        List<RegisterQueueInfo> registerQueueInfos = new ArrayList<>();
        queues.forEach((k, v) -> {
            RegisterQueueInfo registerQueueInfo = new RegisterQueueInfo(k, v, rewrite);
            registerQueueInfos.add(registerQueueInfo);
        });
        SimpleRegister.registerQueues(registerQueueInfos);
        return "";
    }

    private RegisterConnectInfo transfer(SimpleMqCommonConfig simpleMqCommonConfig) {
        return RegisterConnectInfo.build(simpleMqCommonConfig.getHost(), simpleMqCommonConfig.getPort());
    }


    @Bean("annotationBeanPostProcessor")
    public BeanPostProcessor annotationBeanPostProcessor() {
        return new InitAnnotationBeanPostProcessor();
    }

    @Bean("consumerInitEvent")
    public ConsumerInitEvent consumerInitEvent() {
        return new ConsumerInitEvent();
    }

    @Bean("mqSendUtil")
    public MqSendUtil mqSendUtil(SimpleMqCommonConfig simpleMqCommonConfig) {
        MqSendUtil mqSendUtil = new MqSendUtil(simpleMqCommonConfig);
        mqSendUtil.init();
        return mqSendUtil;
    }


}
